package com.wang.helloworld.hellojetty.security;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import com.wang.helloworld.hellojetty.model.Credential;

@Service("authenticationProvider")
public class AuthenticationProviderImpl implements AuthenticationProvider
{
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException 
	{
		Credential credential = new Credential();
		credential.setJ_username((String) authentication.getPrincipal());
		credential.setJ_password((String) authentication.getCredentials());

		validate(credential);

		//securityService.authenticate(credential);
		
		Collection<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
		if(credential.getJ_username().equals("user"))
		{
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("USER");
			grantedAuthorities.add(grantedAuthority);
		}
		else if(credential.getJ_username().equals("jeff"))
		{
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("USER");
			grantedAuthorities.add(grantedAuthority);
			grantedAuthority = new SimpleGrantedAuthority("ADMIN");
			grantedAuthorities.add(grantedAuthority);
		}
		
		return new UsernamePasswordAuthenticationToken(credential.getJ_username(),
				credential.getJ_password(),
                grantedAuthorities);
	}
	
	private void validate(Credential credential)
	{
		//
	}

	@Override
	public boolean supports(Class<?> auth)
	{
		if(UsernamePasswordAuthenticationToken.class.equals(auth))
		{
			return true;
		}

		return false;
	}

}
